package com.hunteron.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

public class DateFormatUtil {
	
	private static final String FULL_FORMAT_DATE_STRING = "yyyy-MM-dd HH:mm:ss";
	private static final String SIMPLE_DAY_STRING = "yyyyMMddHH";
	private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat(FULL_FORMAT_DATE_STRING);

	public static long dateToLong(Date d, long defaultValue) {
		if(d == null) {
			return defaultValue;
		}
		return d.getTime();
	}
	
	public static String formatLong(long millionSeconds) {
		Date date = new Date(millionSeconds);
		return SIMPLE_DATE_FORMAT.format(date);
	}
	public static String formatCurrent() {
		return SIMPLE_DATE_FORMAT.format(new Date());
	}
	
	public static String format(Date d, Date dft) {
		try {
			return SIMPLE_DATE_FORMAT.format(d);
		} catch (Exception e) {
			return SIMPLE_DATE_FORMAT.format(dft);
		}
	}
	
	public static long formateStringToLong(String fmt) {
		try {
			return DateTimeFormat.forPattern(FULL_FORMAT_DATE_STRING).
					parseDateTime(fmt).getMillis();
		} catch (Exception e) {
			e.printStackTrace();
			return System.currentTimeMillis();
		}
	}
	
	public static long offsetDateLong(int h, int minuts, int s) {
		try {
			return new DateTime().plusHours(h).plusMinutes(minuts).plusSeconds(s).getMillis();
		} catch (Exception e) {
			return System.currentTimeMillis();
		}
	}
	public static long offsetDateLong(int days) {
		try {
			return new DateTime().plusDays(days).getMillis();
		} catch (Exception e) {
			return System.currentTimeMillis();
		}
	}

	public static long offsetDateLong(long ms, int h, int minuts, int s) {
		try {
			return new DateTime(ms).plusHours(h).plusMinutes(minuts).plusSeconds(s).getMillis();
		} catch (Exception e) {
			return System.currentTimeMillis();
		}
	}

	public static long deltDayZeroTime(int day) {
		try {
			DateTime date = new DateTime().plusDays(day);
			
			date = date.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfDay(0);
			
			return date.getMillis();
		} catch (Exception e) {
			return System.currentTimeMillis();
		}
	}
	public static long getSimpleDayAsLong(int hours) {
		try {
			String s = new DateTime().plusHours(hours).toString(SIMPLE_DAY_STRING);
			
			return Long.parseLong(s);
		} catch (Exception e) {
			e.printStackTrace();
			return System.currentTimeMillis() / (86400 * 3600);
		}
	}
	
	public static void main(String[] args) {
//		System.out.println(formatLong(offsetDateLong(-25, 0, 0)));
		System.out.println(formatLong(1436941816000L));
		System.out.println(formatLong(deltDayZeroTime(-7)));
		
		System.out.println(getSimpleDayAsLong(-1));
	}
}
